package com.sj.uabrowser.framework;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.sj.uabrowser.BuildConfig;
import com.sj.uabrowser.app.TApp;
import com.sj.uabrowser.db.gen.DaoSession;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Fragment预加载问题的解决方案：
 * 1.可以懒加载的Fragment
 * 2.切换到其他页面时停止加载数据（可选）
 * Created by yuandl on 2016-11-17.
 * blog ：http://blog.csdn.net/linglongxin24/article/details/53205878
 */

public abstract class LazyLoadFragment<P extends BasePresenter> extends Fragment implements BaseView<P> {

    protected BaseActivity<P> act;
    protected P presenter;
    Unbinder unbinder;
    ProgressDialog progressDialog;
    public DaoSession daoSession;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        act = (BaseActivity<P>) context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        presenter = createPresenter();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);
        progressDialog = new ProgressDialog(act);
        daoSession = TApp.getDaoSession();
        isInit = true;
        setView();
        setData();
        /**初始化的时候去加载数据**/
        isCanLoadData();
    }

    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;
    protected final String TAG = "LazyLoadFragment";
    protected View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(setContentView(), container, false);
        return view;
    }

    /**
     * 视图是否已经对用户可见，系统的方法
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }

        if (getUserVisibleHint()) {
            lazyLoad();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        isInit = false;
        isLoad = false;

    }


    /**
     * 设置Fragment要显示的布局
     *
     * @return 布局的layoutId
     */
    protected abstract int setContentView();

    /**
     * 获取设置的布局
     *
     * @return
     */
    protected View getContentView() {
        return view;
    }

    /**
     * 找出对应的控件
     *
     * @param id
     * @param <T>
     * @return
     */
    protected <T extends View> T findViewById(int id) {

        return (T) getContentView().findViewById(id);
    }

    /**
     * 当视图初始化并且对用户可见的时候去真正的加载数据
     */
    protected abstract void lazyLoad();

    /**
     * 当视图已经对用户不可见并且加载过数据，如果需要在切换到其他页面时停止加载数据，可以覆写此方法
     */
    protected void stopLoad() {
    }

    @Override
    public void onDestroy() {
        if (presenter != null) {
            presenter.onDestroy();
            presenter = null;
        }
        super.onDestroy();
    }

    @Override
    public int getLayoutID() {
        return 0;
    }


    @Override
    public void showProgressDialog(String text) {
        progressDialog.setMessage(text);
        progressDialog.show();
    }

    @Override
    public void dismissProgressDialog() {
        progressDialog.dismiss();
    }

    protected void hideKeyBoard(View view) {
        InputMethodManager ims = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        ims.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);
    }

    protected boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }


    @Override
    public void onResume() {
        super.onResume();
        if(BuildConfig.UM) {
            MobclickAgent.onPageStart(this.getClass().getName());
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(BuildConfig.UM) {
            MobclickAgent.onPageEnd(this.getClass().getName());
        }
    }


    @Override
    public void showToast(String text) {
        Toast.makeText(act, text, Toast.LENGTH_SHORT).show();
    }

    public void startIconAnim(View paramView) {
        ScaleAnimation localScaleAnimation = new ScaleAnimation(0.8F, 1.0F, 0.8F, 1.0F, paramView.getWidth() / 2, paramView.getHeight() / 2);
        localScaleAnimation.setDuration(50L);
        paramView.startAnimation(localScaleAnimation);
//        float f1 = paramView.getWidth() / 2;
//        float f2 = paramView.getHeight() / 2;
//        localScaleAnimation = new ScaleAnimation(1.0F, 0.8F, 1.0F, 0.8F, f1, f2);
//        localScaleAnimation.setInterpolator(new BounceInterpolator());
    }
}

